package com.whfc.safety.redis.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.whfc.safety.dto.SafetyDangerDictControlDTO;
import com.whfc.safety.dto.SafetyDangerDictDTO;
import com.whfc.safety.redis.DangerDictRedisDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.List;

/**
 * @Description 查询危大字典缓存
 * @Author hw
 * @Date 2021-08-16 14:53
 * @Version 1.0
 */
@Service
public class DangerDictRedisDaoImpl implements DangerDictRedisDao {

    private static final String DANGER_DICT_KEY = "danger-dict-list";

    private static final String DANGER_DICT_CONTROL_KEY = "danger-dict-control-list::{0}";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void addDangerDict(List<SafetyDangerDictDTO> list) {
        if (list != null && !list.isEmpty()) {
            redisTemplate.opsForValue().set(DANGER_DICT_KEY, JSONObject.toJSONString(list));
        }
    }

    @Override
    public List<SafetyDangerDictDTO> getDangerDict() {
        String json = redisTemplate.opsForValue().get(DANGER_DICT_KEY);
        if (StringUtils.isNotEmpty(json)) {
            return JSONArray.parseArray(json, SafetyDangerDictDTO.class);
        }
        return null;
    }

    @Override
    public void addDangerDictControl(List<SafetyDangerDictControlDTO> list, Integer dictId) {
        if (list != null && !list.isEmpty()) {
            String key = MessageFormat.format(DANGER_DICT_CONTROL_KEY, dictId);
            redisTemplate.opsForValue().set(key, JSONObject.toJSONString(list));
        }
    }

    @Override
    public List<SafetyDangerDictControlDTO> getDangerDictControl(Integer dictId) {
        String key = MessageFormat.format(DANGER_DICT_CONTROL_KEY, dictId);
        String json = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotEmpty(json)) {
            return JSONArray.parseArray(json, SafetyDangerDictControlDTO.class);
        }
        return null;
    }
}
